import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'dart:ui' as ui;
import '../controllers/device_data_controller.dart';
import './fullscreen_chart_view.dart'; // 导入全屏图表视图

class DeviceDataView extends GetView<DeviceDataController> {
  const DeviceDataView({Key? key}) : super(key: key);

  // 重写get controller，确保使用正确的标签获取控制器
  @override
  DeviceDataController get controller {
    final args = Get.arguments as Map<String, dynamic>?;
    final deviceId = args?['deviceId'] as int? ?? 0;
    final deviceName = args?['deviceName'] as String? ?? '';
    
    // 参数校验
    if (deviceId <= 0) {
      print('警告: 设备ID无效 ($deviceId)，请检查页面导航');
      // 可以选择显示错误提示
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (Get.context != null) {
          Get.snackbar(
            '参数错误', 
            '设备ID无效，请返回设备列表重新选择',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.red.withOpacity(0.8),
            colorText: Colors.white,
            duration: const Duration(seconds: 3),
          );
        }
      });
    }
    
    try {
      // 尝试查找已存在的控制器
      return Get.find<DeviceDataController>(tag: 'device_data_$deviceId');
    } catch (e) {
      // 如果找不到，创建一个新的控制器实例
      print('无法找到标签为device_data_$deviceId的控制器，创建新实例');
      final controller = DeviceDataController(
        deviceId: deviceId,
        deviceName: deviceName,
      );
      Get.put<DeviceDataController>(
        controller,
        permanent: true,
        tag: 'device_data_$deviceId',
      );
      return controller;
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    // 添加一个RxBool来控制筛选面板展开/折叠状态
    final isFilterExpanded = true.obs;

    // 预先设置设备名称到AppBar标题
    if (controller.deviceName.isNotEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.appUpdate(); // 更新AppBar标题
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(controller.deviceName.isEmpty ? '设备数据' : '${controller.deviceName}数据'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => controller.refreshData(),
          ),
        ],
      ),
      body: SafeArea(
        child: Obx(() {
          // 显示加载状态
          if (controller.isLoading.value) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    width: 40, 
                    height: 40,
                    child: CircularProgressIndicator(
                      strokeWidth: 3,
                    ),
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    '加载数据中...\n请耐心等待',
                    style: TextStyle(fontSize: 16),
                    textAlign: TextAlign.center,
                  ),
                  if (controller.deviceName.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    Text(
                      '设备: ${controller.deviceName}',
                      style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
                    ),
                  ],
                ],
              ),
            );
          }

          // 显示错误信息
          if (controller.errorMessage.value != null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.error_outline,
                    size: 64,
                    color: theme.colorScheme.error,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    controller.errorMessage.value!,
                    style: TextStyle(
                      color: theme.colorScheme.error,
                      fontSize: 16,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 24),
                  ElevatedButton.icon(
                    onPressed: () => controller.refreshData(),
                    icon: const Icon(Icons.refresh),
                    label: const Text('重试'),
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                    ),
                  ),
                ],
              ),
            );
          }

          // 没有数据时显示提示
          if (controller.chartData.isEmpty || controller.combinedChartData.isEmpty) {
            return Column(
              children: [
                // 可折叠的筛选面板 - 即使没有数据也显示
                _buildCollapsibleFilterPanel(theme, isFilterExpanded),
                
                // 图表内容区域 - 显示无数据提示
                Expanded(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.bar_chart,
                          size: 64,
                          color: theme.disabledColor,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          '暂无历史数据',
                          style: TextStyle(
                            color: theme.disabledColor,
                            fontSize: 16,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '设备尚未上报任何数据',
                          style: TextStyle(
                            color: theme.disabledColor,
                            fontSize: 14,
                          ),
                        ),
                        const SizedBox(height: 24),
                        ElevatedButton.icon(
                          onPressed: () => controller.refreshData(),
                          icon: const Icon(Icons.refresh),
                          label: const Text('刷新'),
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          }

          return Column(
            children: [
              // 可折叠的筛选面板
              _buildCollapsibleFilterPanel(theme, isFilterExpanded),
              
              // 图表部分（使用Expanded确保它占据剩余空间）
              Expanded(
                child: _buildContent(theme),
              ),
            ],
          );
        }),
      ),
    );
  }

  // 新增：提取内容构建逻辑，避免父级Obx触发整个页面重建
  Widget _buildContent(ThemeData theme) {
    return RefreshIndicator(
      onRefresh: () => controller.refreshData(),
      child: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        children: [
          // 图表部分
          _buildChartsSection(theme),
          
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget _buildCollapsibleFilterPanel(ThemeData theme, RxBool isExpanded) {
    return Obx(() => AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      height: isExpanded.value ? null : 56,
      child: Card(
        margin: const EdgeInsets.all(8),
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题栏（始终可见）
            Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () => isExpanded.toggle(),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Row(
                    children: [
                      Text(
                        '筛选选项',
                        style: theme.textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const Spacer(),
                      Icon(
                        isExpanded.value 
                            ? Icons.keyboard_arrow_up 
                            : Icons.keyboard_arrow_down,
                        color: theme.primaryColor,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // 筛选内容（可折叠）
            if (isExpanded.value) ...[
              const Divider(height: 1),
              Padding(
                padding: const EdgeInsets.all(8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 时间范围选择器
                    Row(
                      children: [
                        const Text(
                          '时间范围:',
                          style: TextStyle(fontSize: 14),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: Row(
                              children: [
                                _buildTimeRangeChip('24h', '24小时', theme),
                                const SizedBox(width: 8),
                                _buildTimeRangeChip('7d', '7天', theme),
                                const SizedBox(width: 8),
                                _buildTimeRangeChip('30d', '30天', theme),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    // 显示方式选择器
                    Row(
                      children: [
                        const Text(
                          '显示方式:',
                          style: TextStyle(fontSize: 14),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Obx(() => Row(
                            children: [
                              _buildDisplayModeChip('单独图表', !controller.showCombinedChart.value, theme),
                              const SizedBox(width: 8),
                              _buildDisplayModeChip('组合图表', controller.showCombinedChart.value, theme),
                            ],
                          )),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    ));
  }

  Widget _buildTimeRangeChip(String value, String label, ThemeData theme) {
    final isSelected = controller.timeRange.value == value;

    return GestureDetector(
      onTap: () => controller.changeTimeRange(value),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? theme.primaryColor : Colors.grey.shade200,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey.shade700,
            fontSize: 13,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildDisplayModeChip(String label, bool isSelected, ThemeData theme) {
    return GestureDetector(
      onTap: () {
        if (label == '组合图表' && !controller.showCombinedChart.value) {
          controller.toggleCombinedChart();
        } else if (label == '单独图表' && controller.showCombinedChart.value) {
          controller.toggleCombinedChart();
        }
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? theme.primaryColor : Colors.grey.shade200,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey.shade700,
            fontSize: 13,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildChartsSection(ThemeData theme) {
    return Obx(() {
      // 修改 hasData 逻辑：只检查是否有数据加载，不关心可见性
      final hasLoadedData = controller.chartSeries.isNotEmpty &&
                           controller.chartSeries.any((series) => series.data.isNotEmpty);
      
      // 有可见数据的系列
      final visibleSeries = controller.chartSeries
          .where((series) => series.isVisible.value && series.data.isNotEmpty)
          .toList();

      // 空图表容器高度
      final emptyChartHeight = MediaQuery.of(Get.context!).size.height * 0.4;

      if (!hasLoadedData) {
        // 即使没有数据也返回图表容器，只是在内部显示提示信息
        return Container(
          height: emptyChartHeight,
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.grey.shade300),
          ),
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.bar_chart,
                size: 48,
                color: theme.disabledColor,
              ),
              const SizedBox(height: 16),
              Text(
                '当前时间范围内暂无数据',
                style: TextStyle(
                  color: theme.disabledColor,
                  fontSize: 16,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                '请尝试选择其他时间范围',
                style: TextStyle(
                  color: Colors.grey.shade600,
                  fontSize: 14,
                ),
              ),
            ],
          ),
        );
      }
      
      // 根据显示模式决定构建哪个图表
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildLegendSection(theme),
          const SizedBox(height: 16),
          // 添加条件渲染
          controller.showCombinedChart.value
              ? _buildCombinedChart(theme)
              : _buildSeparateCharts(theme), // 调用单独图表构建方法
        ],
      );
    });
  }
  
  Widget _buildLegendSection(ThemeData theme) {
    // GridView 配置常量
    const crossAxisCount = 4;
    const childAspectRatio = 2.8;
    const mainAxisSpacing = 8.0;  // 增加间距
    const crossAxisSpacing = 6.0;
    const headerHeight = 40.0;  // 标题栏高度

    return Obx(() {
      const estimatedItemHeight = 36.0;  // 略微增加每项高度
      
      // 计算折叠（4行）时的高度，增加更多行显示
      const collapsedHeight = (4 * estimatedItemHeight) + (3 * mainAxisSpacing) + headerHeight;
      
      // 计算展开时的总高度
      final rowCount = (controller.combinedChartData.length / crossAxisCount).ceil();
      final expandedHeight = (rowCount * estimatedItemHeight) + 
                           ((rowCount - 1) * mainAxisSpacing) + 
                           headerHeight;

      // 确定当前目标高度
      final targetHeight = controller.legendsExpanded.value ? expandedHeight : collapsedHeight;

      return AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        height: targetHeight,
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
          color: theme.cardColor,
          borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(controller.legendsExpanded.value ? 8.0 : 0.0),
            bottomRight: Radius.circular(controller.legendsExpanded.value ? 8.0 : 0.0),
          ),
          boxShadow: controller.legendsExpanded.value
              ? [const BoxShadow(color: Colors.black12, blurRadius: 4, offset: Offset(0, 2))]
              : [],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题部分
            Container(
              height: headerHeight,
              padding: const EdgeInsets.only(left: 16, right: 16, top: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '可监测属性',
                    style: theme.textTheme.titleMedium?.copyWith(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  if (controller.combinedChartData.length > 8)
                    TextButton.icon(
                      onPressed: () => controller.toggleLegendsExpansion(),
                      icon: Icon(
                        controller.legendsExpanded.value ? Icons.expand_less : Icons.expand_more,
                        size: 18,
                      ),
                      label: Text(
                        controller.legendsExpanded.value ? '收起' : '显示全部属性',
                        style: const TextStyle(fontSize: 12),
                      ),
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                        minimumSize: const Size(0, 0),
                      ),
                    ),
                ],
              ),
            ),
            // 网格部分
            Expanded(
              child: Container(
                padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
                child: GridView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: crossAxisCount,
                    childAspectRatio: childAspectRatio,
                    crossAxisSpacing: crossAxisSpacing,
                    mainAxisSpacing: mainAxisSpacing,
                  ),
                  itemCount: controller.combinedChartData.length,
                  itemBuilder: (context, i) {
                    return _buildLegendChip(i, theme);
                  },
                ),
              ),
            ),
          ],
        ),
      );
    });
  }
  
  Widget _buildLegendChip(int index, ThemeData theme) {
    final series = controller.combinedChartData[index];
    
    // 检查该属性是否有数据点可以绘制图表
    final canDrawChart = series.data.isNotEmpty; 
    
    // 如果该属性没有数据点可绘制图表，则不显示
    if (!canDrawChart) {
      return const SizedBox.shrink();
    }
    
    // 格式化属性名称，添加单位
    final formattedName = _getFormattedPropertyName(series.name);
    
    return Obx(() => InkWell(
      onTap: () => controller.toggleSeriesVisibility(index),
      borderRadius: BorderRadius.circular(4),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 3),
        decoration: BoxDecoration(
          color: series.isVisible.value ? series.color.withOpacity(0.1) : Colors.grey.shade100,
          borderRadius: BorderRadius.circular(4),
          border: Border.all(
            color: series.isVisible.value ? series.color : Colors.grey.shade300,
            width: 1,
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: 10,
              height: 10,
              decoration: BoxDecoration(
                color: series.isVisible.value ? series.color : Colors.grey.shade400,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(width: 3),
            Expanded(
              child: Text(
                formattedName,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 10,
                  color: series.isVisible.value ? theme.textTheme.bodyMedium?.color : Colors.grey.shade500,
                  fontWeight: series.isVisible.value ? FontWeight.w500 : FontWeight.normal,
                ),
              ),
            ),
          ],
        ),
      ),
    ));
  }

  // 为属性名称添加单位
  String _getFormattedPropertyName(String propertyName) {
    // 标准化属性名称进行比较
    String normalizedName = propertyName.toLowerCase().trim();
    
    // 匹配常见属性名并添加单位
    if (normalizedName.contains('温度') || normalizedName.contains('气温') || normalizedName.contains('水温')) {
      // 如果属性名中已经包含了单位，则不添加
      return propertyName.contains('℃') ? propertyName : '$propertyName(℃)';
    } else if (normalizedName.contains('湿度')) {
      return propertyName.contains('%') ? propertyName : '$propertyName(%)';
    } else if (normalizedName.contains('压') || normalizedName.contains('气压')) {
      return propertyName.contains('hPa') ? propertyName : '$propertyName(hPa)';
    } else if (normalizedName.contains('浊度')) {
      return propertyName.contains('NTU') ? propertyName : '$propertyName(NTU)';
    } else if (normalizedName.contains('盐度')) {
      return propertyName.contains('ppt') ? propertyName : '$propertyName(ppt)';
    } else if (normalizedName.contains('风速')) {
      return propertyName.contains('m/s') ? propertyName : '$propertyName(m/s)';
    } else if (normalizedName.contains('风向')) {
      return propertyName.contains('°') ? propertyName : '$propertyName(°)';
    } else if (normalizedName.contains('雨量') || normalizedName.contains('降水')) {
      return propertyName.contains('mm') ? propertyName : '$propertyName(mm)';
    } else if (normalizedName.contains('辐射') || normalizedName.contains('光照')) {
      return propertyName.contains('lux') ? propertyName : '$propertyName(lux)';
    } else if (normalizedName.contains('电压')) {
      return propertyName.contains('V') ? propertyName : '$propertyName(V)';
    } else if (normalizedName.contains('电流')) {
      return propertyName.contains('A') ? propertyName : '$propertyName(A)';
    } else if (normalizedName.contains('pm2.5')) {
      return propertyName.contains('μg/m³') ? propertyName : '$propertyName(μg/m³)';
    } else if (normalizedName.contains('波高') || normalizedName.contains('hmax') || normalizedName.contains('h3') || normalizedName.contains('h10') || normalizedName.contains('ha') || normalizedName.contains('hm0')) {
      return propertyName.contains('m') ? propertyName : '$propertyName(m)';
    } else if (normalizedName.contains('波周期') || normalizedName.contains('tmax') || normalizedName.contains('t3') || normalizedName.contains('t10') || normalizedName.contains('ta') || normalizedName.contains('tp')) {
      return propertyName.contains('s') ? propertyName : '$propertyName(s)';
    } else if (normalizedName.contains('跨零点') || normalizedName.contains('cropoints')) {
      return propertyName.contains('个') ? propertyName : '$propertyName(个)';
    } else if (normalizedName.contains('波向') || normalizedName.contains('方向谱') || normalizedName.contains('dmean') || normalizedName.contains('dp')) {
      return propertyName.contains('°') ? propertyName : '$propertyName(°)';
    } else if (normalizedName.contains('频率') || normalizedName.contains('fp')) {
      return propertyName.contains('Hz') ? propertyName : '$propertyName(Hz)';
    } else if (normalizedName.contains('深度') || normalizedName.contains('depth')) {
      return propertyName.contains('m') ? propertyName : '$propertyName(m)';
    }
    
    // 如果没有匹配的单位，返回原始名称
    return propertyName;
  }

  Widget _buildCombinedChart(ThemeData theme) {
    return Card(
      margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      clipBehavior: Clip.antiAlias,
      child: Container(
        height: 300,
        padding: const EdgeInsets.all(16),
        child: Obx(() => _buildMultiSeriesChart(controller.combinedChartData, theme)),
      ),
    );
  }

  Widget _buildMultiSeriesChart(List<ChartSeries> seriesList, ThemeData theme) {
    if (seriesList.isEmpty) {
      return const Center(
        child: Text('当前设备暂无历史数据'),
      );
    }

    // 找出所有可见的数据系列，限制最大系列数以提高性能
    final visibleSeries = seriesList.where((s) => s.isVisible.value).toList();
    
    // 性能保护 - 如果可见系列超过12个，只显示前12个
    if (visibleSeries.length > 12) {
      final limitedSeries = visibleSeries.sublist(0, 12);
      
      return Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            margin: const EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(
              color: Colors.deepOrange.withOpacity(0.2),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colors.deepOrange, width: 1),
            ),
            child: Text(
              '已选择${visibleSeries.length}个数据系列，为了保证性能仅显示前12个。',
              style: TextStyle(fontSize: 12, color: Colors.deepOrange.shade800),
              textAlign: TextAlign.center,
            ),
          ),
          Expanded(
            child: _buildChartWithFullscreen(limitedSeries, theme),
          ),
        ],
      );
    }
    
    if (visibleSeries.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.visibility_off,
              size: 32,
              color: theme.disabledColor,
            ),
            const SizedBox(height: 12),
            Text(
              '请选择至少一个数据系列显示',
              style: TextStyle(color: theme.disabledColor),
            ),
          ],
        ),
      );
    }

    // 如果可见的数据系列太多（超过8个但不超过12个），显示一般警告
    if (visibleSeries.length > 8) {
      return Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            margin: const EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(
              color: Colors.amber.withOpacity(0.2),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colors.amber, width: 1),
            ),
            child: Text(
              '已选择${visibleSeries.length}个数据系列，图表可能不易读。建议减少数据系列数量以提高可读性。',
              style: TextStyle(fontSize: 12, color: Colors.amber.shade800),
              textAlign: TextAlign.center,
            ),
          ),
          Expanded(
            child: _buildChartWithFullscreen(visibleSeries, theme),
          ),
        ],
      );
    }
    
    return _buildChartWithFullscreen(visibleSeries, theme);
  }

  Widget _buildChartWithFullscreen(List<ChartSeries> visibleSeries, ThemeData theme) {
    // 添加延迟加载，防止渲染阻塞UI
    return FutureBuilder<ChartData>(
      // 增加10毫秒延迟，让UI优先渲染完成
      future: Future.delayed(const Duration(milliseconds: 10)).then((_) => _prepareChartData(visibleSeries)),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 30,
                  height: 30,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(theme.primaryColor.withOpacity(0.7)),
                  ),
                ),
                const SizedBox(height: 12),
                Text(
                  '图表准备中...',
                  style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                ),
              ],
            ),
          );
        }
        
        final chartData = snapshot.data!;
        
        return GestureDetector(
          onDoubleTap: () {
            // 双击进入全屏
            Get.to(
              () => FullscreenChartView(
                seriesList: visibleSeries,
                theme: theme,
                minY: chartData.minY,
                maxY: chartData.maxY,
                totalPoints: chartData.totalPoints,
              ),
              transition: Transition.fadeIn,
            );
          },
          child: ZoomableChart(
            seriesList: visibleSeries,
            theme: theme,
            minY: chartData.minY,
            maxY: chartData.maxY,
            totalPoints: chartData.totalPoints,
          ),
        );
      },
    );
  }

  // 新增方法：构建单独图表
  Widget _buildSeparateCharts(ThemeData theme) {
    return Obx(() {
      final visibleSeries = controller.combinedChartData
          .where((series) => series.isVisible.value)
          .toList();

      if (visibleSeries.isEmpty) {
        return Container(
          height: 300,
          alignment: Alignment.center,
          child: Text(
            '请至少选择一个属性以显示单独图表',
            style: TextStyle(color: theme.disabledColor, fontSize: 16),
          ),
        );
      }

      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16), // 添加左右边距
        child: Column(
          children: visibleSeries.map((series) {
            return Card(
              margin: const EdgeInsets.only(bottom: 16),
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              clipBehavior: Clip.antiAlias,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _getFormattedPropertyName(series.name),
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 16),
                    SizedBox(
                      height: 200,
                      // 使用 MultiSeriesChartPainter 绘制单个系列
                      child: _buildMultiSeriesChart([series], theme),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      );
    });
  }

  // 添加缺失的数据处理方法
  ChartData _prepareChartData(List<ChartSeries> visibleSeries) {
    // 数据标准化
    double? globalMinY, globalMaxY;
    int totalPoints = 0;
    
    for (final series in visibleSeries) {
      totalPoints += series.data.length;
      for (final point in series.data) {
        globalMinY = (globalMinY == null || point.value < globalMinY) ? point.value : globalMinY;
        globalMaxY = (globalMaxY == null || point.value > globalMaxY) ? point.value : globalMaxY;
      }
    }
    
    if (globalMinY == null || globalMaxY == null) {
      return ChartData(minY: 0, maxY: 1, totalPoints: 0);
    }
    
    return ChartData(
      minY: globalMinY,
      maxY: globalMaxY,
      totalPoints: totalPoints,
    );
  }
}

class SimpleChartPainter extends CustomPainter {
  final List<ChartDataPoint> dataPoints;
  final double minY;
  final double maxY;
  final Color color;

  SimpleChartPainter({
    required this.dataPoints,
    required this.minY,
    required this.maxY,
    required this.color,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    final fillPaint = Paint()
      ..color = color.withAlpha(50) // 使用withAlpha替代withOpacity
      ..style = PaintingStyle.fill;

    final path = Path();
    final fillPath = Path();

    final yRange = maxY - minY;
    final effectiveMinY = minY - yRange * 0.1;
    final effectiveMaxY = maxY + yRange * 0.1;
    final adjustedRange = effectiveMaxY - effectiveMinY;

    // 避免除以零
    if (adjustedRange == 0 || dataPoints.length <= 1) {
      return;
    }

    // 绘制网格线
    final gridPaint = Paint()
      ..color = Colors.grey.withAlpha(50) // 使用withAlpha替代withOpacity
      ..strokeWidth = 0.5;

    // 水平网格线
    for (int i = 0; i <= 5; i++) {
      final y = size.height - (i / 5) * size.height;
      canvas.drawLine(
        Offset(0, y),
        Offset(size.width, y),
        gridPaint,
      );

      // 绘制Y轴标签
      final labelValue = effectiveMinY + (i / 5) * adjustedRange;
      final textSpan = TextSpan(
        text: labelValue.toStringAsFixed(1),
        style: TextStyle(fontSize: 8, color: Colors.grey.shade600),
      );

      final textPainter =
          TextPainter(text: textSpan, textDirection: ui.TextDirection.ltr);
      textPainter.layout();
      textPainter.paint(canvas, Offset(0, y - 10));
    }

    for (int i = 0; i < dataPoints.length; i++) {
      final point = dataPoints[i];

      // 计算X坐标（等间距）
      final x = i / (dataPoints.length - 1) * size.width;

      // 计算Y坐标（映射到画布高度）
      final normalizedY = (point.value - effectiveMinY) / adjustedRange;
      final y = size.height - normalizedY * size.height;

      if (i == 0) {
        path.moveTo(x, y);
        fillPath.moveTo(x, size.height);
        fillPath.lineTo(x, y);
      } else {
        path.lineTo(x, y);
        fillPath.lineTo(x, y);
      }

      // 绘制数据点
      canvas.drawCircle(
        Offset(x, y),
        3,
        Paint()..color = color,
      );
    }

    // 完成填充路径
    fillPath.lineTo(size.width, size.height);
    fillPath.close();

    // 绘制填充区域和线条
    canvas.drawPath(fillPath, fillPaint);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant SimpleChartPainter oldDelegate) {
    return dataPoints != oldDelegate.dataPoints ||
        minY != oldDelegate.minY ||
        maxY != oldDelegate.maxY ||
        color != oldDelegate.color;
  }
}

class MultiSeriesChartPainter extends CustomPainter {
  final List<ChartSeries> seriesList;
  final double minY;
  final double maxY;
  final double scale;
  final double offsetX;
  final int maxPointsPerSeries;  // 添加最大数据点限制

  MultiSeriesChartPainter({
    required this.seriesList,
    required this.minY,
    required this.maxY,
    this.scale = 1.0,
    this.offsetX = 0.0,
    this.maxPointsPerSeries = 100,  // 默认限制每个系列最多100个点
  });

  @override
  void paint(Canvas canvas, Size size) {
    final yRange = maxY - minY;
    final effectiveMinY = minY - yRange * 0.1;
    final effectiveMaxY = maxY + yRange * 0.1;
    final adjustedRange = effectiveMaxY - effectiveMinY;
    
    // 避免除以零
    if (adjustedRange == 0 || seriesList.isEmpty) {
      return;
    }
    
    // 绘制网格线
    final gridPaint = Paint()
      ..color = Colors.grey.withAlpha(50)
      ..strokeWidth = 0.5;
    
    // 水平网格线
    for (int i = 0; i <= 5; i++) {
      final y = size.height - (i / 5) * size.height;
      canvas.drawLine(
        Offset(0, y),
        Offset(size.width, y),
        gridPaint,
      );
      
      // 绘制Y轴标签
      final labelValue = effectiveMinY + (i / 5) * adjustedRange;
      final textSpan = TextSpan(
        text: labelValue.toStringAsFixed(1),
        style: TextStyle(fontSize: 8, color: Colors.grey.shade600),
      );
      
      final textPainter = TextPainter(
        text: textSpan,
        textDirection: ui.TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(canvas, Offset(0, y - 10));
    }

    // 收集所有时间点来确定全局时间范围
    List<DateTime> allTimestamps = [];
    for (final series in seriesList.where((s) => s.isVisible.value)) {
      if (series.data.isEmpty) continue;
      
      allTimestamps.addAll(series.data.map((p) => p.timestamp));
    }
    
    // 对所有时间点排序
    allTimestamps.sort((a, b) => a.compareTo(b));
    
    if (allTimestamps.isEmpty) return;
    
    // 计算全局时间范围
    final firstTime = allTimestamps.first.millisecondsSinceEpoch;
    final lastTime = allTimestamps.last.millisecondsSinceEpoch;
    final fullTimeRange = lastTime - firstTime;
    
    if (fullTimeRange <= 0) return;
    
    // 根据缩放和平移计算可见时间范围
    final visibleTimeRange = fullTimeRange / scale;
    final startOffset = (fullTimeRange - visibleTimeRange) * offsetX;
    final visibleStartTime = firstTime + startOffset.toInt();
    final visibleEndTime = visibleStartTime + visibleTimeRange.toInt();
    
    // 垂直网格线（以时间为基准）
    if (allTimestamps.length > 1) {
      const gridCount = 6;
      for (int i = 0; i <= gridCount; i++) {
        final timestamp = visibleStartTime + (visibleTimeRange / gridCount * i).toInt();
        final x = ((timestamp - visibleStartTime) / visibleTimeRange) * size.width;
        
        canvas.drawLine(
          Offset(x, 0),
          Offset(x, size.height),
          gridPaint,
        );
        
        // 绘制X轴时间标签
        if (i % 2 == 0) { // 只在偶数格显示标签，避免拥挤
          final time = DateTime.fromMillisecondsSinceEpoch(timestamp);
          final timeFormat = DateFormat('HH:mm\nMM-dd');
          final textSpan = TextSpan(
            text: timeFormat.format(time),
            style: TextStyle(fontSize: 8, color: Colors.grey.shade600),
          );
          
          final textPainter = TextPainter(
            text: textSpan,
            textDirection: ui.TextDirection.ltr,
            textAlign: TextAlign.center,
          );
          textPainter.layout();
          textPainter.paint(canvas, Offset(x - textPainter.width / 2, size.height - textPainter.height));
        }
      }
    }
    
    // 为每个系列绘制线条
    for (final series in seriesList.where((s) => s.isVisible.value)) {
      if (series.data.isEmpty) continue;
      
      // 按时间排序
      final allPoints = series.data.toList()
        ..sort((a, b) => a.timestamp.compareTo(b.timestamp));
      
      // 数据点降采样 - 仅在有大量数据点时进行
      final List<ChartDataPoint> points;
      if (allPoints.length > maxPointsPerSeries) {
        // 计算采样间隔
        final samplingRate = (allPoints.length / maxPointsPerSeries).ceil();
        points = [];
        
        // 采样数据点 - 保留第一个和最后一个点，其余按间隔采样
        points.add(allPoints.first);
        for (int i = 1; i < allPoints.length - 1; i += samplingRate) {
          points.add(allPoints[i]);
        }
        if (allPoints.length > 1) {
          points.add(allPoints.last);
        }
      } else {
        points = allPoints;
      }
      
      final paint = Paint()
        ..color = series.color
        ..strokeWidth = 2
        ..style = PaintingStyle.stroke
        ..strokeCap = StrokeCap.round;
      
      final fillPaint = Paint()
        ..color = series.color.withAlpha(30)
        ..style = PaintingStyle.fill;
      
      final path = Path();
      final fillPath = Path();
      
      bool pathStarted = false;
      
      for (int i = 0; i < points.length; i++) {
        final point = points[i];
        final timestamp = point.timestamp.millisecondsSinceEpoch;
        
        // 跳过可见范围外的点
        if (timestamp < visibleStartTime || timestamp > visibleEndTime) {
          continue;
        }
        
        // 计算X坐标（基于时间的相对位置）
        final timeOffset = timestamp - visibleStartTime;
        final x = timeOffset / visibleTimeRange * size.width;
        
        // 计算Y坐标（映射到画布高度）
        final normalizedY = (point.value - effectiveMinY) / adjustedRange;
        final y = size.height - normalizedY * size.height;
        
        // 如果是可见范围内的第一个点
        if (!pathStarted) {
          path.moveTo(x, y);
          fillPath.moveTo(x, size.height);
          fillPath.lineTo(x, y);
          pathStarted = true;
        } else {
          path.lineTo(x, y);
          fillPath.lineTo(x, y);
        }
        
        // 绘制数据点
        canvas.drawCircle(
          Offset(x, y),
          2,
          Paint()..color = series.color,
        );
      }
      
      // 只有当路径有点时才完成填充和绘制
      if (pathStarted) {
        // 完成填充路径
        fillPath.lineTo(size.width, size.height);
        fillPath.close();
        
        // 绘制填充区域和线条
        canvas.drawPath(fillPath, fillPaint);
        canvas.drawPath(path, paint);
      }
    }
  }
  
  @override
  bool shouldRepaint(covariant MultiSeriesChartPainter oldDelegate) {
    return seriesList != oldDelegate.seriesList ||
        minY != oldDelegate.minY ||
        maxY != oldDelegate.maxY ||
        scale != oldDelegate.scale ||
        offsetX != oldDelegate.offsetX ||
        maxPointsPerSeries != oldDelegate.maxPointsPerSeries;
  }
}

// 新增：可缩放图表实现
class ZoomableChart extends StatefulWidget {
  final List<ChartSeries> seriesList;
  final ThemeData theme;
  final double minY;
  final double maxY;
  final int totalPoints;
  
  const ZoomableChart({
    Key? key,
    required this.seriesList,
    required this.theme,
    required this.minY,
    required this.maxY,
    required this.totalPoints,
  }) : super(key: key);

  @override
  _ZoomableChartState createState() => _ZoomableChartState();
}

class _ZoomableChartState extends State<ZoomableChart> with AutomaticKeepAliveClientMixin {
  double _scale = 1.0;
  double _offsetX = 0.0;
  double? _startScale;
  double? _startOffsetX;
  Offset? _lastFocalPoint;
  
  // 添加缓存图表功能
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);  // 必须调用，AutomaticKeepAliveClientMixin的要求
    
    final visibleSeries = widget.seriesList.where((s) => s.isVisible.value).toList();
    
    if (visibleSeries.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.visibility_off,
              size: 32,
              color: widget.theme.disabledColor,
            ),
            const SizedBox(height: 12),
            Text(
              '请选择至少一个数据系列显示',
              style: TextStyle(color: widget.theme.disabledColor),
            ),
          ],
        ),
      );
    }
    
    // 使用FutureBuilder延迟图表计算，避免卡顿
    return FutureBuilder<ChartData>(
      // 将耗时计算放入Future中异步执行
      future: Future.microtask(() => _prepareChartData(visibleSeries)),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        
        final chartData = snapshot.data!;
        
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: GestureDetector(
                onScaleStart: (details) {
                  _startScale = _scale;
                  _startOffsetX = _offsetX;
                  _lastFocalPoint = details.focalPoint;
                },
                onScaleUpdate: (details) {
                  setState(() {
                    // 处理缩放
                    if (_startScale != null) {
                      _scale = (_startScale! * details.scale).clamp(1.0, 10.0);
                    }
                    
                    // 处理平移
                    if (_lastFocalPoint != null && details.scale == 1.0) {
                      final dx = details.focalPoint.dx - _lastFocalPoint!.dx;
                      final availableDx = MediaQuery.of(context).size.width;
                      
                      if (availableDx > 0) {
                        final newOffsetX = _offsetX - (dx / availableDx);
                        _offsetX = newOffsetX.clamp(0.0, 1.0);
                      }
                    }
                    
                    _lastFocalPoint = details.focalPoint;
                  });
                },
                onScaleEnd: (details) {
                  _startScale = null;
                  _startOffsetX = null;
                  _lastFocalPoint = null;
                },
                child: Stack(
                  children: [
                    CustomPaint(
                      size: Size.infinite,
                      painter: MultiSeriesChartPainter(
                        seriesList: visibleSeries,
                        minY: chartData.minY,
                        maxY: chartData.maxY,
                        scale: _scale,
                        offsetX: _offsetX,
                        // 根据数据点数量动态调整采样率
                        maxPointsPerSeries: chartData.totalPoints > 1000 ? 100 : 200,
                      ),
                    ),
                    // 缩放说明
                    Positioned(
                      top: 8,
                      right: 8,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.6),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          '缩放倍数: ${_scale.toStringAsFixed(1)}x',
                          style: const TextStyle(color: Colors.white, fontSize: 10),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              height: 30,
              alignment: Alignment.center,
              child: Text(
                '双指缩放或拖动图表可查看更多细节',
                style: TextStyle(fontSize: 10, color: Colors.grey.shade600),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        );
      },
    );
  }
  
  // 提取耗时计算到单独的方法中
  ChartData _prepareChartData(List<ChartSeries> visibleSeries) {
    // 数据标准化
    double? globalMinY, globalMaxY;
    int totalPoints = 0;
    
    for (final series in visibleSeries) {
      totalPoints += series.data.length;
      for (final point in series.data) {
        globalMinY = (globalMinY == null || point.value < globalMinY) ? point.value : globalMinY;
        globalMaxY = (globalMaxY == null || point.value > globalMaxY) ? point.value : globalMaxY;
      }
    }
    
    if (globalMinY == null || globalMaxY == null) {
      return ChartData(minY: 0, maxY: 1, totalPoints: 0);
    }
    
    return ChartData(
      minY: globalMinY,
      maxY: globalMaxY,
      totalPoints: totalPoints,
    );
  }
}

// 添加图表数据类用于在Future中传递计算结果
class ChartData {
  final double minY;
  final double maxY;
  final int totalPoints;
  
  ChartData({
    required this.minY,
    required this.maxY,
    required this.totalPoints,
  });
}
